package com.calciominoBeta.Activity;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.calciominoBeta.R;
import com.calciominoBeta.Activity.db.DbSupport;
import com.calciominoBeta.Activity.db.TableDb;
import com.calciominoBeta.Activity.task.Task;
import com.calciominoBeta.Activity.task.TaskType;
import com.calciominoBeta.Adapter.Accueil_Adapter;
import com.calciominoBeta.Entity.InfoOj;
import com.calciominoBeta.Util.Sdata;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.telpoo.frame.object.BaseObject;
import com.telpoo.frame.ui.BaseActivity;
import com.telpoo.frame.utils.Mlog;

@SuppressLint("ResourceAsColor")
public class Detail_Activity extends BaseActivity {

	private TextView tv_title, tv_date_text, tv_author, tv_type, tv_content,
			html;
	private WebView webView;
	private Accueil_Adapter adapter;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected DisplayImageOptions options;
	private ImageView img_next, img_prev, img_back, img_share, img_share_post;
	ArrayList<InfoOj> dataLv = null;
	Integer position = 1;
	ListView lv_accueil;
	protected int itemHeight;
	// private InterstitialAd interstitial;
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accueil_adapter);
		getItemHeigh();
		dataLv = Sdata.dataLv;
		position = Sdata.position;
		Sdata.dataLv = null;
		Sdata.position = null;
		tv_title = (TextView) findViewById(R.id.tv_title1);
		tv_date_text = (TextView) findViewById(R.id.tv_date_text1);
		tv_type = (TextView) findViewById(R.id.tv_type1);
		img_next = (ImageView) findViewById(R.id.img_next);
		img_prev = (ImageView) findViewById(R.id.img_prev);
		webView = (WebView) findViewById(R.id.web);
		lv_accueil = (ListView) findViewById(R.id.detail_list);
		img_share = (ImageView) findViewById(R.id.img_share);
		img_share_post = (ImageView) findViewById(R.id.img_share_post);
		img_share_post.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				share();
			}
		});
		img_share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				share();
			}
		});

		adView = (AdView) findViewById(R.id.ad);
		AdRequest adRequest = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("")
				.build();
		adView.loadAd(adRequest);

		img_next.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View arg0) {
				
				if(position<dataLv.size()-1)
				updateUI(position++);
			}
		});
		img_prev.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				if(position>0)
				updateUI(position--);
			}
		});
		img_back = (ImageView) findViewById(R.id.img_back);
		img_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		File cacheDir = StorageUtils.getOwnCacheDirectory(Detail_Activity.this,
				"Calciomino/imageCache");
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisc(true).build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				Detail_Activity.this)
				.threadPoolSize(3)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(new UsingFreqLimitedMemoryCache(2000000))
				.discCache(new UnlimitedDiscCache(cacheDir))
				.memoryCacheSize(1500000)
				// 1.5 Mb

				.denyCacheImageMultipleSizesInMemory()
				.discCache(new UnlimitedDiscCache(cacheDir))
				.discCacheFileNameGenerator(new Md5FileNameGenerator()).build();

		imageLoader.init(config);

		updateUI(position);
		adapter = new Accueil_Adapter(Detail_Activity.this, imageLoader,
				options);
		lv_accueil.setAdapter(adapter);
		loadDataObjHome();

	}

	private void updateUI(int position) {

		String id = dataLv.get(position).get(InfoOj.ID);
		getData(id);

	}

	void share() {
		InfoOj oj = new InfoOj();
		String title = oj.get(oj.get(InfoOj.TITLE));
		Intent share = new Intent(android.content.Intent.ACTION_SEND);
		share.setType("text/plain");
		share.putExtra(Intent.EXTRA_TEXT, title);
		startActivity(Intent.createChooser(share, "Calciomino"));
	}

	void loadDataObjHome() {
		// Util.CheckNewWork();
		// String json = "";
		// NetConfig config = new NetConfig.Builder().build();
		// BaseNetSupportBeta.getInstance().init(config);
		//
		// json = BaseNetSupportBeta.getInstance().method_GET(
		// "http://www.calciomio.fr/json-exports/home");
		// new ArrayList<InfoOj>();
		// try {
		// JSONArray jsonArray = new JSONArray(json);
		// for (int i = 0; i < 5; i++) {
		//
		// JSONObject joj = jsonArray.getJSONObject(i);
		// InfoOj infoAccueil = Util.parseJsonAccueil(joj);
		// adapter.addData(infoAccueil);
		// }
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		ArrayList<InfoOj> dataHome = DbSupport.getCache(TableDb.HOME);
		ArrayList<InfoOj> dataHome1 = new ArrayList<InfoOj>();
		for (int i = 0; i < 5; i++) {
			dataHome1.add(dataHome.get(i));
		}
		adapter.setData(dataHome1);

		// LayoutParams lp = (LayoutParams) lv_accueil.getLayoutParams();
		// lp.height = itemHeight*5;
		// lv_accueil.setLayoutParams(lp);
	}

	// note
	private void getData(String id) {

		ArrayList<String> list = new ArrayList<String>();
		list.add(id);

		new Task(model, TaskType.DETAIL, list, getBaseContext()).exe();
		showProgressDialog(Detail_Activity.this);

	}

	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		super.onSuccess(taskType, list, msg);

		if (taskType == TaskType.DETAIL) {
			closeProgressDialog();
			BaseObject ojj = (BaseObject) list.get(0);
			InfoOj infoDetail = new InfoOj();
			infoDetail.setParams(ojj.getParams());

			// tv_type.setText(infoDetail.getC_type());
			if (infoDetail.get(InfoOj.TYPE).equalsIgnoreCase("breves")) {
				tv_type.setText(R.string.breves);
				tv_type.setTextColor(getResources().getColorStateList(
						R.color.breves));
			}
			if (infoDetail.get(InfoOj.TYPE).equalsIgnoreCase("videos")) {
				tv_type.setText(getString(R.string.video_fr));
				tv_type.setTextColor(getResources().getColorStateList(
						R.color.video));
			}
			if (infoDetail.get(InfoOj.TYPE).equalsIgnoreCase("articles")) {
				tv_type.setText("ARTICLES");
				tv_type.setTextColor(getResources().getColorStateList(
						R.color.articles));
			}
			tv_title.setText(infoDetail.get(InfoOj.TITLE));
			tv_title.setTextColor(getResources().getColorStateList(
					R.color.detail_title));
			tv_date_text.setText(infoDetail.get(InfoOj.DATE_TEXT));

			StringBuilder mhtml = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0,target-densityDpi=device-dpi\" />\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />\n</head>\n<body>\n")
					.append(infoDetail.get(InfoOj.CONTENT)).append(
							"\n</body>\n</html>");
			
			
			//String a=""+"";
			
			webView.loadDataWithBaseURL("", mhtml.toString(), "text/html",
					"utf-8", "");

			lv_accueil.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {

					Accueil_Adapter madapter = (Accueil_Adapter) arg0
							.getAdapter();

					ArrayList<InfoOj> arrNews = madapter.getFull();
					Sdata.dataLv = arrNews;
					Sdata.position = position;
					startActivity(new Intent(Detail_Activity.this,
							Detail_Activity.class));

				}
			});

		}

	}

	private void getItemHeigh() {
		LayoutInflater inflater = getLayoutInflater();
		final View v = inflater.inflate(R.layout.custom_accueil_adapter, null,
				false);

		ViewTreeObserver observer = v.getViewTreeObserver();
		observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@Override
			public void onGlobalLayout() {

				v.getViewTreeObserver().removeGlobalOnLayoutListener(this);

				if (v.getHeight() > 0) {
					itemHeight = v.getHeight();

					Mlog.T("" + itemHeight);
					lv_accueil.getLayoutParams().height = (itemHeight * 11);
					((RelativeLayout) findViewById(R.id.tmm)).removeView(v);

				}

			}
		});

		((RelativeLayout) findViewById(R.id.tmm)).addView(v);

	}

}
